package com.hee.erp.modules.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hee.erp.annotation.Log;
import com.hee.erp.modules.entity.SysLog;
import com.hee.erp.modules.entity.SysUser;
import com.hee.erp.modules.mapper.SysLogMapper;
import com.hee.erp.modules.service.ISysLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hee.erp.modules.service.ISysUserService;
import com.hee.erp.pojo.LoginInfo;
import com.hee.erp.util.CommonUtils;
import com.hee.erp.util.IPUtils;
import com.hee.erp.vo.FiltersOption;
import com.hee.erp.vo.ListFilterOption;
import com.hee.erp.vo.Sorter;
import com.hee.erp.vo.LogListParams;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author weizehong
 * @since 2022-03-15
 */
@Service
@Transactional
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements ISysLogService {

    @Autowired
    IPUtils ipUtils;

    @Autowired
    ISysUserService sysUserService;


    @Override
    public void saveLog(JoinPoint joinPoint, Log log, LoginInfo loginInfo) {
        HttpServletRequest request = loginInfo.getRequest();

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        String invokeMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        String requestIp = request.getRemoteAddr();
        //首先从历史log中根据ip查询
        String requestAddr = this.getAddressByIp(requestIp);

        if (StringUtils.isEmpty(requestAddr)) {
            requestAddr = ipUtils.getCityInfo(requestIp);
        }
        String requestMethod = request.getMethod();
        String requestUrl = request.getRequestURL().toString();

        StringBuffer sbParams = new StringBuffer();
        if (RequestMethod.POST.name().equals(requestMethod)) {
            //post 处理json参数
            LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
            String[] paramNames = u.getParameterNames(method);
            Object[] args = joinPoint.getArgs();
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof HttpServletRequest || args[i] instanceof HttpServletResponse || args[i] instanceof MultipartFile) {
                    continue;
                }
                sbParams.append(paramNames[i] + ":" + JSON.toJSONString(args[i]));
                if (i != args.length - 1) {
                    sbParams.append(",");
                }
            }
        }

        SysLog sysLog = new SysLog();
        sysLog.setDescription(log.value());
        sysLog.setMethod(invokeMethod);
        sysLog.setParams(sbParams.toString());
        sysLog.setRequestUrl(requestUrl);
        sysLog.setRequestIp(requestIp);
        sysLog.setRequestAddr(requestAddr);
        this.save(sysLog);
    }

    private String getAddressByIp(String requestIp) {
        LambdaQueryWrapper<SysLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysLog::getRequestIp, requestIp);
        queryWrapper.last(" limit 1 ");
        SysLog one = this.getOne(queryWrapper);
        if (one == null) {
            return "";
        }
        return one.getRequestAddr();
    }

    @Override
    public SysLog getDetailById(String id) {

        SysLog sysLog = this.getById(id);
        SysUser sysUser = sysUserService.getById(sysLog.getCreateUser());
        sysLog.setCreateUserName(sysUser.getUserName());

        return sysLog;
    }

    @Override
    public IPage<SysLog> listByPage(LogListParams params) {

        Integer pageSize = params.getPageSize();
        Integer current = params.getCurrent();
        IPage<SysLog> page = new Page<>(current, pageSize);

        QueryWrapper queryWrapper = createQueryWrapper(params);

        this.page(page, queryWrapper);
        setDetails(page.getRecords());

        return page;
    }

    private QueryWrapper createQueryWrapper(LogListParams params) {
        QueryWrapper<SysLog> queryWrapper = new QueryWrapper<>();

        LogListParams.Filters filters = params.getFilters();
        Sorter sorter = params.getSorter();
        LogListParams.Condition condition = params.getCondition();

        //列表筛选
        if (filters != null) {
            if(filters.getCreateUserName() != null && filters.getCreateUserName().size() > 0){
                queryWrapper.lambda().in(SysLog::getCreateUserName, filters.getCreateUserName());
            }
        }

        //工具栏搜索
        if (StringUtils.isNotBlank(condition.getDescription())) {
            queryWrapper.lambda().like(SysLog::getDescription, condition.getDescription());
        }
        if(condition.getCreateDate() != null){
            queryWrapper.lambda().like(SysLog::getCreateTime, condition.getCreateDate());
        }

        //排序
        CommonUtils.setQueryOrderCondition(queryWrapper, sorter);

        return queryWrapper;
    }

    @Override
    public List<FiltersOption> getFiltersOptions() {
        List<FiltersOption> filtersOptions = new ArrayList<>();
        FiltersOption filtersOption = new FiltersOption();

        //createUserName
        filtersOption.setColumnKey("createUserName");
        List<ListFilterOption> options = createCreateUserNameFiltersOption();
        filtersOption.setOptions(options);

        filtersOptions.add(filtersOption);
        return filtersOptions;
    }

    private List<ListFilterOption> createCreateUserNameFiltersOption() {

        QueryWrapper<SysLog> queryWrapper = new QueryWrapper<>();
        //选择不重复的create_user
        queryWrapper.select(" distinct(create_user) create_user ");
        List<SysLog> list = this.list(queryWrapper);

        List<String> userIdList = list.stream().map(entity -> entity.getCreateUser()).collect(Collectors.toList());
        List<SysUser> userList = sysUserService.listByIds(userIdList);

        List<ListFilterOption> options = userList.stream().map(entity -> {
            ListFilterOption option = new ListFilterOption();
            option.setValue(entity.getId());
            option.setText(entity.getUserName());
            return option;
        }).collect(Collectors.toList());

        return options;
    }

    private void setDetails(List<SysLog> records) {
        //根据records 获取createUser 集合
        List<String> createUserIdList = records.stream().map(sysLog -> sysLog.getCreateUser()).collect(Collectors.toList());

        if (createUserIdList.size() > 0) {
            List<SysUser> sysUserList = sysUserService.listByIds(createUserIdList);
            records.forEach(sysLog -> {
                Optional<SysUser> any = sysUserList.stream().filter(user -> user.getId().equals(sysLog.getCreateUser())).findAny();
                SysUser sysUser = any.orElse(new SysUser());
                sysLog.setCreateUserName(sysUser.getUserName());

            });
        }
    }
}
